﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Helpers;
using Kugar.UI.Web.AdminLTE.Models;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageForms
{
    public class PageForm_MultiFileUploadField2: PageForm_SingleInputFieldBase
    {
        private IEnumerable<UploadFileInfo> _data = null;
        private bool _disabled = false;
        private string _mime = "";
        private string _uploadUrl = "";
        private int _fileSize = 0;
        private string _onUploadSuccess = "";
        private int _maxFileQty = -1;

        public PageForm_MultiFileUploadField2(PageForm_Form form, ViewContext viewContext) : base(form, viewContext)
        {
            this.Css("webui-form_multifileuploadfield2 multifileuploader2");
            _controlWidth = "45%";
        }

        /// <summary>
        /// 文件数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 FileUrls(IEnumerable<UploadFileInfo> data)
        {
            _data = data;

            return this;
        }

        public PageForm_MultiFileUploadField2 FileUrls(IEnumerable<SelectorItem> fileUrls)
        {
            _data = fileUrls.Select(x=>new UploadFileInfo(x.Title,x.Value, deleteable:x.Disabled)).ToArrayEx();

            return this;
        }

        /// <summary>
        /// 文件数据
        /// </summary>
        /// <typeparam name="TData"></typeparam>
        /// <param name="lst">数据源</param>
        /// <param name="titleGetter">获取标题的函数</param>
        /// <param name="srcGetter">获取文件路径的函数</param>
        /// <param name="disableGetter"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 FileUrls<TData>(IEnumerable<TData> lst, Func<TData, string> titleGetter,
            Func<TData, string> srcGetter, Func<TData, bool> disableGetter = null)
        {
            _data = lst.Select(x => new UploadFileInfo(titleGetter(x), srcGetter(x), deleteable:disableGetter?.Invoke(x) ?? false)).ToArrayEx();

            return this;
        }


        /// <summary>
        /// 是否禁用该控件(不允许增加和删除文件)
        /// </summary>
        /// <param name="disabled"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 Disabled(bool disabled)
        {
            _disabled = disabled;
            return this;
        }

        /// <summary>
        /// 允许上传的MIME类型
        /// </summary>
        /// <param name="mime"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 AcceptMime(string mime)
        {
            _mime = mime;
            return this;
        }

        /// <summary>
        /// 文件上传地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 UploadUrl(string url)
        {
            _uploadUrl = url;

            return this;
        }

        /// <summary>
        /// 可上传的最大大小,单位为KB
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 MaxFileSize(int size)
        {
            _fileSize = size * 1024;

            return this;
        }

        /// <summary>
        /// 可上传的文件数量
        /// </summary>
        /// <param name="qty"></param>
        /// <returns></returns>
        public PageForm_MultiFileUploadField2 MaxFileQty(int qty)
        {
            _maxFileQty = qty;

            return this;
        }

        protected override void BeforeRender(TextWriter writer)
        {
            this.Data("name", _name);
            this.Data("uploadurl", _uploadUrl)
                .Data("maxfilesize", _fileSize.ToStringEx())
                .Data("maxfileqty",_maxFileQty.ToStringEx())
                .Data("disabled", _disabled.ToStringEx())
                .Data("accept", _mime)
                ;

            base.BeforeRender(writer);
        }

        protected override void RenderContent(TextWriter writer)
        {
            var dataJson = JsonConvert.SerializeObject(_data,
                new JsonSerializerSettings() {StringEscapeHandling = StringEscapeHandling.EscapeHtml});


            writer.WriteLine($"<input class=\"allfileinfo\" type=\"hidden\" name=\"{_name}__FileInfo\" value=\"\" />");
            writer.WriteLine("<table class=\"table table-bordered table-striped filetable\" webui-ignore lay-ignore style=\"display: table;margin-bottom: 0px;\">");
            writer.WriteLine($"<thead><tr><th width=\"30px\"></th><th width=\"100%\">文件名</th><th width=\"25%\">");

            if (!_disabled)
            {
                writer.WriteLine($"<button type=\"button\" class=\"btn btn-success btn-xs addfile\" {_disabled.If("disabled")}>选择文件</button>");
            }

            writer.WriteLine("</th></tr></thead>");
            writer.WriteLine("<tbody>");

            if (_data.HasData()) 
            {
                foreach (var item in _data)
                {
                    writer.WriteLine($"<tr data-fileinfo-mime=\"{HttpUtility.HtmlEncode(item.Mime)}\" data-fileinfo-title=\"{HttpUtility.HtmlEncode(item.Title)}\" >");
                    writer.WriteLine($"<td><i class=\"fileIcon fa fa-fw {getMimeIcon(Path.GetExtension(item.FileUrl),item.Mime)}\"></i></td>");

                    writer.WriteLine($"<td class=\"filename\" ><span>{item.Title}</span><input class=\"fileurl\" type=\"hidden\" name=\"{_name}\" value=\"{item.FileUrl}\" /></td>");
                    
                    writer.WriteLine("<td class=\"buttonlist\">");

                    if (item.Viewable)
                    {
                        writer.Write("<a class=\"badge bg-info badge-view\">查看</a>");
                    }
                    
                    if (item.Deleteable && !_disabled)
                    {
                        writer.Write("<br/><a class=\"badge bg-red badge-del\">删除</a>");
                    }

                    writer.Write("</td>");

                    writer.WriteLine("</tr>");
                }
            }


            writer.WriteLine("</tbody>");
            writer.WriteLine("</table>");
        }

        private string getMimeIcon(string extName,string mime)
        {
            mime = mime.ToLower();
            extName = extName.ToLower();

            if (mime.Contains("image"))
            {
                return "fa-file-image-o";
            }
            else if (extName==".pdf" || mime.Contains("pdf"))
            {
                return "fa-file-pdf-o";
            }
            else if (mime.Contains("excel") || mime.Contains("sheet"))
            {
                return "fa-file-excel-o";
            }
            else if (extName==".doc" || extName==".docx" || mime.Contains("msword") || mime.Contains("wordprocessingml.document"))
            {
                return " fa-file-word-o";
            }
            else
            {
                return "fa-file-o";
            }
        }
    }
}
